<template>
  <view class="search-result">
    <!-- 搜索栏 -->
    <view class="search-header">
      <search-input
        v-model="keyword"
        :show-cancel="true"
        @confirm="handleSearch"
        @cancel="handleBack"
      ></search-input>
    </view>

    <!-- 搜索结果 -->
    <view class="result-content">
      <!-- 结果统计 -->
      <view class="result-stats" v-if="total > 0">
        <text>共找到 {{ total }} 个相关商品</text>
      </view>

      <!-- 商品列表 -->
      <waterfall-flow
        :products="products"
        @item-click="handleProductClick"
      ></waterfall-flow>

      <!-- 加载更多 -->
      <uni-load-more :status="loadMoreStatus"></uni-load-more>

      <!-- 空状态 -->
      <view class="empty-state" v-if="products.length === 0 && !isLoading">
        <image src="/static/images/empty-search.png" mode="aspectFit"></image>
        <text>未找到相关商品</text>
        <text class="tip">换个关键词试试吧</text>
      </view>
    </view>
  </view>
</template>

<script>
import SearchInput from '@/components/search/SearchInput.vue'
import WaterfallFlow from '@/components/common/WaterfallFlow.vue'

export default {
  components: {
    SearchInput,
    WaterfallFlow
  },
  data() {
    return {
      keyword: '',
      products: [],
      total: 0,
      pageNum: 1,
      pageSize: 20,
      loadMoreStatus: 'more',
      isLoading: false
    }
  },
  onLoad(options) {
    if (options.keyword) {
      this.keyword = decodeURIComponent(options.keyword).trim()
      if (this.keyword) {
        this.search()
      } else {
        uni.showToast({
          title: '请输入有效的搜索关键词',
          icon: 'none'
        })
      }
    }
  },
  onReachBottom() {
    if (this.loadMoreStatus === 'more') {
      this.loadMore()
    }
  },
  methods: {
    // 执行搜索
    async search() {
      if (!this.keyword) {
        uni.showToast({
          title: '请输入搜索关键词',
          icon: 'none'
        })
        return
      }

      const trimmedKeyword = this.keyword.trim()
      if (!trimmedKeyword) {
        uni.showToast({
          title: '请输入有效的搜索关键词',
          icon: 'none'
        })
        return
      }

      this.pageNum = 1
      this.products = []
      this.loadMoreStatus = 'loading'
      this.isLoading = true

      try {
        const res = await this.$api.product.search.simple({
          keyword: trimmedKeyword,
          pageNum: this.pageNum,
          pageSize: this.pageSize
        })

        if (res.code === 200 && res.data) {
          this.products = this.processProducts(res.data.records)
          this.total = res.data.total || 0
          this.loadMoreStatus = this.products.length < this.pageSize ? 'noMore' : 'more'

          // 记录搜索行为
          try {
            await this.$api.product.search.recordHistory(trimmedKeyword)
          } catch (error) {
            console.error('记录搜索历史失败:', error)
          }
        } else {
          throw new Error(res.message || '搜索失败')
        }
      } catch (error) {
        console.error('搜索失败:', error)
        uni.showToast({
          title: error.message || '搜索失败',
          icon: 'none'
        })
        this.loadMoreStatus = 'more'
      } finally {
        this.isLoading = false
      }
    },

    // 加载更多
    async loadMore() {
      if (this.isLoading || this.loadMoreStatus !== 'more') return

      this.loadMoreStatus = 'loading'
      this.isLoading = true
      this.pageNum++

      try {
        const res = await this.$api.product.search.simple({
          keyword: this.keyword.trim(),
          pageNum: this.pageNum,
          pageSize: this.pageSize
        })

        if (res.code === 200 && res.data) {
          const newProducts = this.processProducts(res.data.records)
          this.products = [...this.products, ...newProducts]
          this.loadMoreStatus = newProducts.length < this.pageSize ? 'noMore' : 'more'
        } else {
          throw new Error(res.message || '加载失败')
        }
      } catch (error) {
        console.error('加载更多失败:', error)
        this.pageNum--
        this.loadMoreStatus = 'more'
        uni.showToast({
          title: error.message || '加载失败',
          icon: 'none'
        })
      } finally {
        this.isLoading = false
      }
    },

    // 处理商品数据
    processProducts(records) {
      if (!Array.isArray(records)) return []
      
      return records.map(item => ({
        id: item.id,
        name: item.name,
        mainImage: item.mainImage,
        price: item.price,
        originalPrice: item.originalPrice,
        sales: item.sales,
        subtitle: item.subtitle,
        stock: item.stock,
        status: item.status,
        isRecommend: item.isRecommend === 1,
        isNew: item.isNew === 1,
        isHot: item.isHot === 1,
        viewCount: item.viewCount
      }))
    },

    // 处理搜索
    handleSearch() {
      this.search()
    },

    // 处理返回
    handleBack() {
      uni.navigateBack()
    },

    // 处理商品点击
    handleProductClick(product) {
      const id = product.id || product.productId
      if (!id) return
      
      // 直接跳转到商品详情页，不再记录点击行为
      uni.navigateTo({
        url: `/pages/product/detail/index?id=${id}`
      })
    }
  }
}
</script>

<style lang="scss" scoped>
.search-result {
  min-height: 100vh;
  background-color: #f5f5f5;
}

.search-header {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  z-index: 100;
  background-color: #fff;
}

.result-content {
  padding-top: 96rpx;
  min-height: 200rpx;
}

.result-stats {
  padding: 20rpx;
  font-size: 24rpx;
  color: #999;
  background-color: #fff;
  margin-bottom: 20rpx;
}

.empty-state {
  padding: 120rpx 0;
  display: flex;
  flex-direction: column;
  align-items: center;
  background-color: #fff;

  image {
    width: 240rpx;
    height: 240rpx;
    margin-bottom: 30rpx;
  }

  text {
    font-size: 28rpx;
    color: #333;
    margin-bottom: 10rpx;

    &.tip {
      font-size: 24rpx;
      color: #999;
    }
  }
}
</style> 